package com.zhz.mall.portal.controller;

import com.zhz.mall.common.api.CommonResult;
import com.zhz.mall.common.util.jwt.JwtTokenUtil;
import com.zhz.mall.portal.contant.UserErrorCode;
import com.zhz.mall.portal.modules.ums.model.UmsMember;
import com.zhz.mall.portal.modules.ums.service.UmsMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/***
 * @author zhouhengzhe
 */
@RestController
@Api("前台用户服务接口")
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UmsMemberService memberService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public CommonResult<UmsMember> register(@Validated @RequestBody UmsMember umsMemberParam) {
        UmsMember umsAdmin = memberService.register(umsMemberParam);
        return Objects.isNull(umsAdmin) ? CommonResult.failed() : CommonResult.success(umsAdmin);
    }

    @ApiOperation("登录")
    @PostMapping("/login")
    public CommonResult<Map<String, String>> login(@Validated @RequestBody UmsMember umsMemberParam) {
        UmsMember login = memberService.login(umsMemberParam.getUsername(), umsMemberParam.getPassword());
        if (Objects.isNull(login)) {
            return CommonResult.validateFailed(UserErrorCode.USERNAME_OR_PASSWORD_FAIL.getMessage());
        }
        String token = jwtTokenUtil.generateUserNameStr(login.getUsername());
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        tokenMap.put("tokenHeader", tokenHeader);
        // jwt
        return CommonResult.success(tokenMap);
    }
}
